<?php
/**
 * Created by PhpStorm.
 * User: dt
 * Time: 16:33
 */
namespace  backend\models;

use Yii;
use yii\web\IdentityInterface;
use backend\base\BaseModel;


/**
 * 后台用户
 * @package app\models
 */
class AdminModel extends BaseModel implements IdentityInterface{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admin';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'create_time', 'status','creator_id'], 'integer','message'=>'{attribute}必须是整数'],
            [['username','role'], 'string', 'max' => 40],
            [['password'], 'string', 'max' => 100],
            [['mobile'],'match','pattern'=>'/^1[34578]{1}\d{9}$/','message'=>'手机号错误！'],
            //登录场景
            [['mobile'], 'unique', 'on' => ['add','edit'], 'message' => '{attribute}已被注册'],
            [['mobile', 'password'], 'required', 'on' => ['login'], 'message' => '{attribute}不能为空'],
            [['username','password','role','mobile'],'required', 'on'=> ['add'], 'message' => '{attribute}不能为空'],
            [['mobile','role'], 'required', 'on' => ['edit'], 'message' => '{attribute}不能为空'],
            [['id'], 'required', 'on' => ['delete','edit_pass'], 'message' => '{attribute}不能为空'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => '登录名',
            'password' => '登录密码',
            'create_time' => '创建时间',
            'creator_id' => '创建人',
            'status' => '状态',
            'mobile' => '手机号',
            'role' => '角色',
        ];
    }

    /**
     * 保存前
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert)){
            $time = time();
            if($this->isNewRecord){
                $this->create_time = $time;
                $this->status = 1;
                $this->password = Yii::$app->security->generatePasswordHash($this->password);
            }
            return true;
        }
        return false;
    }

    /**
     * 登录
     * @param $username
     * @return static
     */
    public function loginValidate()
    {
        $admin = self::findIdentityByUsername($this->mobile);
        if (empty($admin)) {return false;}//用户不存在
        if (Yii::$app->security->validatePassword($this->password, $admin->password)) {//存在，验证密码，验证通过返回identity实例
            return $admin;
        }
        return false;
    }

    /*
     * 用户新增
     */
    public function userAdd($data)
    {
        return self::save();
    }

    /*
     * 用户列表
     */
    public function getList($data)
    {
        $condition = "status != 0 ";
        if(!empty($data['mobile'])){
            $condition .= " and mobile like '%".$data['mobile']."%'";
        }
        if(!empty($data['username'])){
            $condition .= " and username like '%".$data['username']."%'";
        }
        $result = self::find()->where($condition);
        if(!empty($data['page'])){
            $num = ($data['page']-1)*15;
            $result = $result->offset($num);
        }
        if(!empty($data['limit'])){
            $result = $result->limit($data['limit']);
        }
        $retern['data'] = $result->asArray()->all();
        $retern['count'] = self::find()->where($condition)->count();
        return $retern;
    }

/*<<<<<<<<<<<<<以下是继承yii2登录校验时候默认要重写的一些方法不能删除>>>>>>>>>>>>>>>>>*/

    /**
     * 根据ID返回identity实例
     * @param int|string $id
     * @return static
     */
    public static function findIdentity($id)
    {
        $tmpIdentity   = static::findOne(['id' => $id]);
        return $tmpIdentity;
    }

    /**
     * 根据用户名返回identity实例
     * @param $username
     * @return static
     */
    public static function findIdentityByUsername($username)
    {
        return static::findOne(['mobile' => $username]);
    }

    /**
     * 根据access_token返回identity实例
     * @param mixed $token
     * @param null $type
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        // TODO: Implement findIdentityByAccessToken() method.
    }

    /**
     * 返回ID
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * cookie记住我 - 返回cookie中auth_key
     * @return mixed
     */
    public function getAuthKey()
    {
        //return $this->auth_key;
    }

    /**
     * cookie记住我 - 验证
     * @param string $authKey
     * @return bool
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['mobile' => $username]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
    }
    
}
